package com.example.provider;

import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.os.Bundle;
import android.util.Log;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Uri allContacts = ContactsContract.Contacts.CONTENT_URI;

        Cursor c;
        CursorLoader cursorLoader = new CursorLoader(this, allContacts, null, null, null, null);
        c = cursorLoader.loadInBackground();

        String[] columns = new String[]{
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID
        };

        int[] views = new int[] {R.id.contactName,  R.id.contactID};

        SimpleCursorAdapter adapter;

        adapter = new SimpleCursorAdapter(this, R.layout.activity_main, c, columns, views, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        this.setListAdapter(adapter);

        printContacts(c);
    }

    private void printContacts(Cursor c){
        if(c.moveToFirst()){
            do{
                String contactID = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                String contactName = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Log.v("Contact Providers", contactID + ", " + contactName);

                int hasPhone = c.getInt(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                if(hasPhone == 1){
                    Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactID, null, null);

                    while (phoneCursor.moveToNext()){
                        Log.v("Contact Providers", phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                    }
                }
            }while (c.moveToNext());
        }
    }
}
